import data from '@/data/shop/product/product-detail.js';
import initConfig from '@/mixins/shop/product/product-detail.js';
import style from '@/common/js/style.js';
import BigNumber  from "@/common/js/bignumber.js"
// #ifdef APP-PLUS-NVUE
const bindingx = uni.requireNativePlugin('bindingx');
const dom = uni.requireNativePlugin('dom');
// #endif

const customData = {
	old: {
		pageScrollTop: 0,
	},
	pageSectionList: ['product', 'comment', 'detail', 'recommended'],
};

export default {
	mixins: [initConfig],
	data() {
		return {
			// 初始化的一些数据
			pageScrollTop: 0,
			
			navBarBgOpacity: 0,
			navBarTitleOpacity: 0,
			navBarSideIconBgColor: 'rgba(0, 0, 0, 0.3)',
			navBarSideIconTextColor: '#FFF',
			navBarSideIconTextOpacity: 1,				
			
			navBarHeight: 0,
			currentNavBarTitleIconIndex: 0,
			navBarTitleIconContentTopList: [], //标题对应内容距离顶部距离
			showCloseVideoBtn: false,
			
			currentImageIndex: 0,
			videoScrollRate: 0.5,
			videoTransX: 0,
			videoTransY: 0,
			videoHeightDynamic: 0,
			videoIsFloat: false,
			showVideo: false,
			imageList: [],
			video: '',
			price: '',
			stock:0,
			marketPrice: '',
			title: '',
			goodsThumb:"",
			goodsAttr:[],		// 商品属性
			goodsStorage:[],	//商品管库
			list:[],
			
			addressList:[],
			discountList: [],
			commentTotal: '',
			goodCommentPercent: '',
			commentList: [],
			
			productInfoImageLoadedCount: 0,
			productInfoImageList: [],
			productInfoImageAspectRatioList: [],
			specificationList: [],
			
			stocked : 1, 	//选择的库存数
			
			recommendedProductList: [], 	//为你推荐
			
			clickFlag:true
		}
	},
	computed: {
		// 视频窗口配置参数
		videoWidth() {
			return this.toPx('750rpx');
		},
		videoFloatWidth() {
			return this.toPx(this.productMediaConfig.videoFloat.width);
		},
		videoHeight() {//初始高度
			return this.toPx(this.productMediaConfig.height);
		},
		videoFloatHeight() {
			return this.toPx(this.productMediaConfig.videoFloat.height);
		},
		videoFloatOffsetTop() {
			return this.toPx(style.UNI_SPACING_ROW_BASE);
		},
		videoFloatOffsetRight() {
			return this.toPx(style.UNI_SPACING_COL_BASE);
		},
		
		rateSize() {
			return this.toPx(this.rateConfig.starSize);
		},
		commentListLength() {
			return this.commentList.length;
		},
		productInfoImageListImage() {
			return this.productInfoImageList.map((item) => {
				return item.image;
			})
		},
		productInfoImageListCount() {
			return this.productInfoImageList.length;
		},
		address(){
			return this.addressList.length>0 && this.addressList.filter(item=>item.selected).length>0 ? this.addressList.filter(item=>item.selected)[0]['address']:"请选择地址";
		},
		hasVideo(){
			return !((this.video.length && this.video.length==0) || Object.keys(this.video).length==0);
		},
		//是否收藏该商品
		hasCollect(){
			return this.list.is_collect == 1;
		},
		/* *
		*  对选中属性的计算操作
		* arrIds	:选中的属性id列表
		* arrAttrs	:选中的属性值列表
		* select_attr_str	:选中后展示的串
		*/
		getGoodsAttrSelectedExt(){
			let arrIds=[],arrAttrs=[],select_attr_str="请选择";
			this.goodsAttr.forEach((attr,attrIndex)=>{
				let attr_selected = attr.attr_list.filter(item=>item.checked);
				if(attr_selected.length>0){
					arrIds.push(attr_selected[0].id);
					arrAttrs.push(attr_selected[0].attr_value);
				}
			});
			return {
				ids:arrIds.length==0?"":arrIds.join(","),
				attrs:arrAttrs.length==0?"":(arrAttrs.lenght==1?arrAttrs[0]:arrAttrs.join(" ")),
				attrsStr:arrAttrs.length==0 ? 
					"请选择" : ("已选择 "+(arrAttrs.lenght==1?arrAttrs[0]:arrAttrs.join(" ")+"，"+this.stocked+"件"))
				
			}
		},
		realityPrice(){
			let amount = new BigNumber(this.price);
			this.goodsAttr.forEach((attr,attrIndex)=>{
				let attr_selected = attr.attr_list.filter(item=>item.checked);
				if(attr_selected.length>0) amount = amount.plus(attr_selected[0].attr_price);
			});
			return amount.toNumber();
		},
		goodsAttrStr(){
			let goodsAttr = this.goodsAttr , default_str = "请选择", str="已选择";
			this.goodsAttr.forEach((attr,attrIndex)=>{
				default_str+=" "+attr.name;
				let attr_selected = attr.attr_list.filter(item=>item.checked);
				if(attr_selected.length>0) str+=" "+attr_selected[0].attr_value;
			})
			return str.length>3?str + "，"+this.stocked+"件":default_str;
		}
	},
	async onLoad(option) {
		let id = option.id || 1;
		let address_id = option.address_id || 0;
		//配置
		this.videoHeightDynamic = this.videoHeight;
		
		//初始化的一些数据
		const productData = data.product();
		const addressListData = data.userAddressList();
		const discountListData = data.discountList(); 
		const commentInfoData = data.commentInfo();
		const productInfoImageListData = data.productInfoImageList();
		const recommendedProductListData = data.recommendedProductList();
		const specificationListData =data.specificationList();
		
		const product = await productData;
		this.imageList = product.photo;
		this.video = product.video;
		this.price = product.price;
		this.stock = product.stock;
		this.marketPrice = product.market_price;
		this.title = product.goods_name;
		this.goodsThumb = product.goods_thumb;
		this.goodsAttr = product.goods_attr;
		this.addressList = await addressListData;
		this.discountList = await discountListData;
		this.list.content = product.content;
		
		const commentInfo = await commentInfoData;
		this.commentTotal = commentInfo.total;
		this.goodCommentPercent = commentInfo.goodCommentPercent;
		this.commentList = commentInfo.commentList;
		
		this.productInfoImageList = await productInfoImageListData;
		this.specificationList = await specificationListData;
		
		this.recommendedProductList = await recommendedProductListData;
		
		
		// #ifdef MP-WEIXIN
		uni.showShareMenu({withShareTicket:true});
		// #endif
		
		// #ifdef MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO
		uni.showShareMenu();
		// #endif
	},
	
	onReady() {
		this.$nextTick(function () {
			setTimeout(() => {
				this.calculateLayout();
			}, 1000);
			this.$watch('productInfoImageLoadedCount', (newVal, oldVal) => {
				console.log(newVal,this.productInfoImageListCount);
				if (newVal === this.productInfoImageListCount) {
					setTimeout(() => {
						this.calculateLayout();
					}, 100);
				}
			});
		})
	},
	methods: {
		// #ifdef APP-NVUE
		getComponentRect(ref) {
			
			const dom = uni.requireNativePlugin('dom');
			
			return new Promise(function (resolve, reject) {
				dom.getComponentRect(ref, data => {
					resolve(data);
				})
			})
		},
		getEl: function(el) {
			if (typeof el === 'string' || typeof el === 'number') return el;
			if (WXEnvironment) {
				return el.ref;
			} else {
				return el instanceof HTMLElement ? el : el.$el;
			}
		},
		// #endif
		toPx(value) {
			const result = /(\d+\.?\d*)(\w+)/.exec(value);
			if ('rpx' === result[2].trim()) {
				return uni.getSystemInfoSync().screenWidth * Number(result[1]) / 750;
			} else if('px' === result[2].trim()) {
				return Number(result[1]);
			} else {
				throw new TypeError(`${value}单位格式不正确`);
			}
		},
		
		async calculateLayout() {
			// #ifndef APP-PLUS-NVUE
			const selector = uni.createSelectorQuery().in(this);
			selector.select('.product').fields({size: true});
			selector.select('.comment').fields({size: true});
			selector.select('.detail').fields({size: true});
			selector.select('.recommended').fields({size: true});
			selector.exec(data => {
				let sumHeight = 0;
				data.forEach((item, index) => {
					this.navBarTitleIconContentTopList[index] = sumHeight - this.navBarHeight;
					sumHeight += item.height;
				})
			});
			// #endif
			
			// #ifdef APP-PLUS-NVUE
			const productData = this.getComponentRect(this.$refs['product']);
			const commentData = this.getComponentRect(this.$refs['comment']);
			const detailData = this.getComponentRect(this.$refs['detail']);
			// const recommendedData = this.getComponentRect(this.$refs['recommended']);
			
			const productHeight = (await productData).size.height;
			const commentHeight = (await commentData).size.height;
			const detailHeight = (await detailData).size.height;
			// const recommendedHeight = (await recommendedData).size.height;
			
			this.navBarTitleIconContentTopList[0] = 0;
			this.navBarTitleIconContentTopList[1] = productHeight - this.navBarHeight;
			this.navBarTitleIconContentTopList[2] = productHeight + commentHeight - this.navBarHeight;
			this.navBarTitleIconContentTopList[3] = productHeight + commentHeight + detailHeight - this.navBarHeight;
			
			// #endif
		},
		
		pageScroll(e) {
			let scrollTop;
			// #ifndef APP-PLUS-NVUE
			scrollTop = e.detail.scrollTop;
			// #endif
			
			// #ifdef APP-PLUS-NVUE
			scrollTop = -e.contentOffset.y;
			// #endif
			
			customData.old.pageScrollTop = scrollTop;
			
			//设置顶部导航与滚动联动，根据滚动位置选择当前导航项
			let offsetY = scrollTop + 10;
			if (offsetY > this.navBarTitleIconContentTopList[0] && offsetY < this.navBarTitleIconContentTopList[1]) {
				this.currentNavBarTitleIconIndex = 0;
			} else if (offsetY > this.navBarTitleIconContentTopList[1] && offsetY < this.navBarTitleIconContentTopList[2]) {
				this.currentNavBarTitleIconIndex = 1;
			} else if (offsetY > this.navBarTitleIconContentTopList[2] && offsetY < this.navBarTitleIconContentTopList[3]) {
				this.currentNavBarTitleIconIndex = 2;
			} else if (offsetY > this.navBarTitleIconContentTopList[3]) {
				this.currentNavBarTitleIconIndex = 3;
			}
			
			//设置导航栏背景及按钮随滚动渐变
			const threshold = 100;
			const changePosition = 0.5;
			this.navBarBgOpacity = this.$Helper.between(scrollTop/threshold, 0, 1);
			this.navBarTitleOpacity = this.$Helper.between(scrollTop/threshold, 0, 1);
			this.navBarSideIconBgColor = `rgba(0, 0, 0, ${0.3*this.$Helper.between((1 - scrollTop/(threshold/2)), 0, 1)})`;
			this.navBarSideIconTextColor = scrollTop < (threshold/2) ? '#FFF' : '#000';
			this.navBarSideIconTextOpacity = scrollTop < (threshold/2) ? this.$Helper.between(1 - scrollTop/(threshold/2), 0, 1) : this.$Helper.between(scrollTop/(threshold/2) - 1, 0, 1);
			
			//导航栏关闭视频播放
			this.showCloseVideoBtn = (scrollTop < 10 && this.showVideo === true) ? true : false;
			
			this.videoIsFloat = scrollTop < this.videoHeight ? false : true;
		},
		
		getNavBarMaxHeight(e) {
			this.navBarHeight = e;
		},
		navBarLeftIconTap(id) {
			const action = {
				back() {
					uni.navigateBack({
						delta: 1
					});
				}
			};
			
			action[id]();
		},
		colseVideoBtnTap() {
			this.showVideo = false;
			this.showCloseVideoBtn = false;
		},
		navBarTitlteIconTap(index) {
			
			// #ifndef APP-PLUS-NVUE
			this.pageScrollTop = customData.old.pageScrollTop;
			this.$nextTick(function () {
				this.pageScrollTop = this.navBarTitleIconContentTopList[index];
			})
			// #endif
			
			// #ifdef APP-PLUS-NVUE
			const toSectionRef = this.getEl(this.$refs[customData.pageSectionList[index]]);
			
			dom.scrollToElement(toSectionRef, {offset: -this.navBarHeight, animated: false});
			// #endif
			
			setTimeout(() => {
				this.currentNavBarTitleIconIndex = index;
			}, 300);
		},
		
		playVideoBtnTap() {
			//设置视频窗口及关闭视频窗口按钮显示
			this.showVideo = true;
			this.showCloseVideoBtn = true;
			
			//设置初始视频窗口位置
			this.videoTransY = -customData.old.pageScrollTop*this.videoScrollRate;
			this.videoHeightDynamic = this.videoHeight - customData.old.pageScrollTop*(1 - this.videoScrollRate);
			
			this.$nextTick(function () {
				// #ifdef APP-PLUS-NVUE
				const pageScrollRef = this.getEl(this.$refs['page-scroll']);
				const productVideoRef = this.getEl(this.$refs['product-video']);
				bindingx.bind({
				  eventType:'scroll', //描述事件触发类型是scroll触发
				  anchor: pageScrollRef, //滚动容器
				  props:[  //props数组用来描述伴随scroll事件需要改变的元素节点
					
					{
					  element: productVideoRef, //动画元素
					  property:'height', //动画属性
					  expression:`y < ${this.videoHeight-20} ? ${this.videoHeight} - y*(${1-this.videoScrollRate}) : ${this.videoFloatHeight}` //表达式 说明了y从0-400,对应的值是1-0  
					},
					{
					  element: productVideoRef, //动画元素
					  property:'width', //动画属性
					  expression:`y < ${this.videoHeight-20} ? ${this.videoWidth} : ${this.videoFloatWidth}` //表达式 说明了y从0-400,对应的值是1-0  
					},
					{
					  element: productVideoRef, //动画元素
					  property:'transform.translateX', //动画属性
					  expression:`y < ${this.videoHeight-3} ? 0 : ${-this.videoFloatOffsetRight}` //表达式 说明了y从0-400,对应的值是1-0  
					},
					{
					  element: productVideoRef, //动画元素
					  property:'transform.translateY', //动画属性
					  expression:`y < ${this.videoHeight} ? y*(-${this.videoScrollRate}) : ${this.navBarHeight + this.videoFloatOffsetTop}` //表达式 说明了y从0-400,对应的值是1-0  
					},
				  ]
				}, function (res) {
					// console.log(res);
				});
				// #endif
			})
		},
		productImageChange(e) {
			this.currentImageIndex = e.detail.current;
		},
		videoFloatCloseBtnTap() {
			this.showVideo = false;
		},
		
		//产品详情图片加载
		productInfoImageLoad(index, e) {
			this.$set(this.productInfoImageAspectRatioList, index,  e.detail.height / e.detail.width)
			this.productInfoImageLoadedCount++;
		},
		producInfoImageTap(url, index) {
			if (url) {
				uni.navigateTo({
					url: url,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			} else {
				uni.previewImage({
					current: index,
					urls: this.productInfoImageListImage,
				});
			}
		},
		//选择活动与优惠
		showPop(mark){ 
			mark==="activity" && this.$refs.activity.open();
			mark==="cart" && this.$refs.cart.open();
			mark==="address" && this.$refs.address.open();
		},
		closePop(mark){
			mark==="activity" && this.$refs.activity.close();
			mark==="cart" && this.$refs.cart.close();
			mark==="address" && this.$refs.address.close();
		},
		selectAddress(address_id){
			for (let index in this.addressList) {
				//this.addressList[index].selected = this.addressList[index].id==address_id?true:false;
				this.addressList[index].id == address_id ? this.$set(this.addressList[index],"selected",true):this.$set(this.addressList[index],"selected",false);
			}
		},
		selectGoodsAttr(attr_id,attr_child_id){
			let arrIds=[];
			this.stock = this.list.stock;
			this.goodsThumb = this.list.goods_thumb;
			this.goodsAttr.forEach((attr,attrIndex)=>{
				if(attr.id === attr_id){
					attr.attr_list.forEach((child,childIndex)=>{
						child.id==attr_child_id?this.$set(this.goodsAttr[attrIndex].attr_list[childIndex],"checked",true):this.$set(this.goodsAttr[attrIndex].attr_list[childIndex],"checked",false);
					});
				}
				let attr_selected = attr.attr_list.filter(item=>item.checked);
				if(attr_selected.length>0){
					arrIds.push(attr_selected[0].id);
				}
			});
			
			if(arrIds.length == this.goodsAttr.length){
				this.stocked=1;
				this.goodsStorage.forEach((storage,storageIndex)=>{
					if(arrIds.join(",")==storage.goods_attr_ids){
						this.stock = storage.stock;
						if(storage.thumb.length>0) this.goodsThumb = storage.thumb;
					}
				});
			}
		},
		settlement(e){
			try{
				this.goodsAttr.forEach((attr,attrIndex)=>{
					if(attr.attr_list.filter(item=>(item.checked)).length == 0){
						throw new Error(attr.name+"必须");
					}
				});
			}catch(e){
				this.$Helper.tpfToast({title:e.message});
				return false;
			}
			let param = {
				id:this.list.id,
				quantity:this.stocked,
				spec_key:this.getGoodsAttrSelectedExt.ids,
				spec_key_name:this.getGoodsAttrSelectedExt.attrs
			};
			console.log(this.stock,this.stocked);
			if(this.stock==0 || this.stock<this.stocked){
				this.$Helper.tpfToast({title:"库存不足"});return false;
			}
			// 添加购物车
			if(e=="addToCart"){
				this.$Helper.tpfToast({title:"功能开发中..."});
			}
		
			if(e == "goBuy"){
				this.$Helper.tpfJump({url:`/pages/shop/settlement/settlement?id=${param.id}&quantity=${param.quantity}&spec_key=${param.spec_key}&spec_key_name=${param.spec_key_name}`});
			}
		},
		iconTap(e){
			let that = this;
			let action = {
				follow(){
					if(!that.clickFlag) return false;
					that.priceSectionConfig.iconList.forEach((icon,iconItem)=>{
						if(icon.id == e){
							that.clickFlag = false;
							
							if(that.hasCollect){
								that.$set(that.priceSectionConfig.iconList[iconItem],"title","\ue662");
								that.$set(that.priceSectionConfig.iconList[iconItem],"subtitle","关注");
								that.$set(that.priceSectionConfig.iconList[iconItem],"appendStyle","");
								that.$set(that.list,"is_collect",0);
							}else{
								that.$set(that.priceSectionConfig.iconList[iconItem],"title","\ue68a");
								that.$set(that.priceSectionConfig.iconList[iconItem],"subtitle","已关注");
								that.$set(that.priceSectionConfig.iconList[iconItem],"appendStyle","color:#F00;");
								that.$set(that.list,"is_collect",1);
							}
							setTimeout(()=>{
								that.clickFlag = true;
							},1000);
							
						}
					});
				}
			};
			
			if(action[e]){
				action[e]();
			}else{
				console.log("功能开发中");
			}
			
		}
	},
	
}